import { parse } from '@/utils/historyUtils';
import { Spin } from 'antd';
import React, { useEffect } from 'react';
import { history, useModel } from 'umi';

export default (): React.ReactNode => {
    const { initialState, setInitialState } = useModel('@@initialState');

    const goto = async () => {
        if (!history) return;

        // 如果不是登录页面，执行
        const { location } = history;

        console.log('====================', location);

        // 如果没有登录，重定向到 login
        const { token, route, request, param } = parse(location.search) as {
            token: string;
            route: string;
            request: string;
            param: string;
        };

        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
            setInitialState({
                ...initialState,
                currentUser: userInfo,
            });
            setTimeout(() => {
                if (history.replaceState) {
                    history.replaceState(null, document.title, route);
                    history.go(0);
                } else {
                    history.replace(route);
                }
            }, 100);
        }
        window.addEventListener('message', function (e) {
            history.push(e.data.route);
        });
    };

    useEffect(() => {
        goto();
    }, []);

    return (
        <div
            style={{
                textAlign: 'center',
                marginTop: 20,
                marginBottom: 20,
            }}
        >
            <Spin size="large" />
        </div>
    );
};
